package com.cash.app.ui.main.fg.repay

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.cash.app.R
import com.cash.app.constant.AppConstant.REPAY_CHANNEL_APP
import com.cash.app.constant.AppConstant.REPAY_CHANNEL_BROWSER
import com.cash.app.databinding.FgRepayBinding
import com.cash.app.ui.main.fg.repay.adapter.RepayListAdapter
import com.cash.app.ui.order.LoanInfoActivity
import com.cash.app.ui.order.LoanListActivity
import com.cash.app.ui.other.RepayActivity
import com.cash.app.utils.NumberUtils
import com.cash.app.utils.ThirdAppUtils
import com.cash.app.utils.addVerticalSpacing

class RepayFragment : Fragment() {

    private var _binding: FgRepayBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: RepayViewModel
    private lateinit var adapter: RepayListAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this)[RepayViewModel::class.java]
        _binding = FgRepayBinding.inflate(inflater, container, false)
        viewModel.getRepayList()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        setupEmptyState()
        setupObservers()
        setupClickListeners()
        setupSwipeRefresh()
    }

    override fun onResume() {
        super.onResume()
        viewModel.getRepayList()
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefreshLayout.setColorSchemeResources(
            R.color.app_theme_color,
        )
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            viewModel.getRepayList()
        }
    }

    private fun setupRecyclerView() {
        adapter = RepayListAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = this@RepayFragment.adapter
            addVerticalSpacing(resources.getDimensionPixelSize(R.dimen.home_list_item_spacing))
        }

        adapter.onRepayClickListener = { item ->
            viewModel.getRepayUrl(item.o_id)
        }
        adapter.onItemClickListener = { item ->
            LoanInfoActivity.start(requireContext(), item.o_id)
        }
    }

    private fun setupEmptyState() {
        binding.emptyState.apply {
            setEmptyText(getString(R.string.repay_data_empty_tip))
            setEmptyImage(R.mipmap.home_data_empty)
        }
    }

    private fun setupObservers() {
        viewModel.repayData.observe(viewLifecycleOwner) { data ->
            binding.swipeRefreshLayout.isRefreshing = false
            binding.header.totalAmount.text = NumberUtils.toRupeeWithComma(data.order_money)
            adapter.setData(data.order_list)
        }

        viewModel.showEmptyState.observe(viewLifecycleOwner) { showEmpty ->
            binding.swipeRefreshLayout.isRefreshing = false
            binding.emptyState.visibility = if (showEmpty) View.VISIBLE else View.GONE
            binding.recyclerView.visibility = if (showEmpty) View.GONE else View.VISIBLE
        }

        viewModel.repayInfo.observe(viewLifecycleOwner) { response ->
            if (response.jump_to_url.isEmpty()) {
                Toast.makeText(
                    requireContext(), getString(R.string.repay_url_error), Toast.LENGTH_SHORT
                ).show()
            }
            when (response.repay_channel) {
                REPAY_CHANNEL_APP -> {
                    RepayActivity.start(requireContext(), response.jump_to_url)
                }

                REPAY_CHANNEL_BROWSER -> {
                    ThirdAppUtils.openInSystemBrowser(requireContext(), response.jump_to_url)
                }

                else -> {
                    ThirdAppUtils.openInSystemBrowser(requireContext(), response.jump_to_url)
                }
            }
        }
    }

    private fun setupClickListeners() {
        binding.header.loanHistory.setOnClickListener {
            val intent = Intent(requireContext(), LoanListActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}